<template>
  <transition name="as-move-to-right">
    <div class="as-notification"
         :class="['as-notification--'+type]"
         ref="message"
         @mouseenter="enter"
         @mouseout="leave"
         :style="{top}"
         v-show="visible">
      <i :class="messageIcon" v-if="messageIcon"></i>
      <span class="title">{{title||'标题'}}</span>
      <div class="content">
        <span class="message">{{message}}</span>
      </div>
    </div>
  </transition>
</template>

<script type="text/ecmascript-6">
export default {
  name: "",
  data() {
    return {
      type: ""
    };
  },
  watch: {
    instances(newVal, oldVal) {
      let top = 0;

      let index = newVal.indexOf(this);

      if (index > -1) {
        newVal.forEach((instance, instanceIndex) => {
          if (index > instanceIndex) {
            top += instance.$el.offsetHeight + 10;
          }
        });
        this.top = top + 20 + "px";
      }
    }
  },
  computed: {
    messageIcon() {
      if (this.icon) {
        return this.icon;
      }
      if (this.type) {
        switch (this.type) {
          case "success":
            return "el-icon-success";
            break;
          case "warning":
            return "el-icon-warning";
            break;
          case "error":
            return "el-icon-error";
            break;
          case "info":
            return "el-icon-info";
            break;
          default:
            return "";
        }
      }
    }
  },
  mounted() {
    this.visible = true;
    this.leave();
  },
  methods: {
    enter() {
      clearTimeout(this.timeout);
    },
    leave() {
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.timeout = setTimeout(() => {
        this.visible = false;
        this.instances.splice(this.instances.indexOf(this), 1);
        setTimeout(() => {
          if (document.body.contains(this.$el)) {
            document.body.removeChild(this.$el);
          }
        }, 1500);
      }, this.duration || 3000);
    }
  }
};
</script>
